﻿using SqlSugar;
using WeDonekRpc.Helper;
using WeDonekRpc.SqlSugar.VirtualQuery;

namespace WeDonekRpc.SqlSugar.DBHelper
{
    public class DBTools : IDBTools
    {
        private readonly ISqlClientFactory _Factory;

        private readonly string _ConfigId;

        protected DBTools ( ISqlClientFactory factory, string configId )
        {
            this._Factory = factory;
            this._ConfigId = configId;
        }
        private SqlSugarProvider _Provider;

        public SqlSugarProvider Provider
        {
            get
            {
                this._Provider ??= this._Factory.GetProvider(this._ConfigId);
                return this._Provider;
            }
        }
        public List<DbTableInfo> GetAllTable ( bool isCache = true )
        {
            return this.Provider.DbMaintenance.GetTableInfoList(isCache);
        }
        public bool IsView ( string viewName, bool isCache = true )
        {
            return this.Provider.DbMaintenance.GetViewInfoList(isCache).IsExists(c => c.Name == viewName);
        }
        public List<DbTableInfo> GetAllView ( bool isCache = true )
        {
            return this.Provider.DbMaintenance.GetViewInfoList(isCache);
        }
        public bool IsTable ( string tableName, bool isCache = true )
        {
            return this.Provider.DbMaintenance.IsAnyTable(tableName, isCache);
        }
        public bool TruncateTable ( string tableName )
        {
            if ( this.IsTable(tableName) )
            {
                return this.Provider.DbMaintenance.TruncateTable(tableName);
            }
            return false;
        }
        public void EditView ( string name, QueryStruct body )
        {
            VirtualQuery.VirtualQuery t = new VirtualQuery.VirtualQuery(this.Provider);
            t.Load(body);
            string sql = t.ToSql();
            sql = string.Format("{0} view {1} as \r\n {2}", this.IsView(name) ? "alter" : "create", name, sql);
            _ = this.Provider.Ado.ExecuteCommand(sql);
        }
        public bool DropView ( string name )
        {
            return this.Provider.DbMaintenance.DropView(name);
        }
    }
}
